<template>
  <div class="work-container">
    <!-- 如果数据还未加载，显示加载提示 -->
    <div v-if="loading">加载中...</div>
    <div v-else>
      <div v-for="(category, index) in worklist" :key="index">
        

        <el-row :gutter="20">
          <!-- 循环展示每一个分类下的剧本 -->
          <el-col v-for="script in category.scripts" :key="script.wid" :xs="6" :sm="6" :md="6" :lg="4" :xl="3" class="work-item">
            <el-card class="work-card" @click="goToWorkProfile(script.wid)">
              <img :src="'http://localhost:8080/api/images/' + script.wimage" alt="小说封面" class="novel-image" />
              <div class="novel-info">
                <h3 class="novel-title">{{ script.wname }}</h3>
                <p class="novel-description">
                  简介：{{ script.introduction.length > 6 ? script.introduction.substring(0, 6) + '...' : script.introduction }}
                </p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject, onMounted, defineEmits } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import CryptoJS from 'crypto-js';
import { defineProps } from 'vue';

const props = defineProps<{ uid: number | string }>();

// 获取路由对象和 Router
const route = useRoute();
const router = useRouter();
const axios = inject('axios'); // 注入 axios

// 定义 emit 事件，用于向父组件传递数据
const emit = defineEmits<{
  (e: 'update-script-count', count: number): void;
}>();

// 定义存储从 API 获取的数据
const worklist = ref<Array<{ typename: string, scripts: Array<any> }>>([]);
const scriptCount = ref(0); // 定义剧本统计数量
const loading = ref(true); // 加载状态

// 获取登录的 Token
function getToken() {
  const encryptedToken = localStorage.getItem('token');
  if (encryptedToken) {
    const secretKey = 'your_secret_key'; // 使用相同的密钥
    const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
    const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
    return decryptedToken;
  }
  return null;
}

// 用户数据
const user = ref({});

// 初始化用户信息
function initUser() {
  console.log('获取用户信息');
  const Token = getToken();
  if (Token) {
    axios({
      method: 'get',
      url: 'http://localhost:8080/user/getuser',
      headers: {
        Authorization: 'Bearer ' + Token
      }
    })
      .then(response => {
        if (response.data.code === '200') {
          user.value = response.data.user;
          console.log("用户信息获取成功------------：" + JSON.stringify(response.data.user));
        }
      })
      .catch(error => {
        console.error("用户信息获取失败", error);
      });
  }
}

// 查询剧本列表和分类信息
const getWorkList = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/getworklist');
    if (response.data.code === 200) {
      worklist.value = response.data.data;
      console.log("Work List:", worklist.value);
    }
  } catch (error) {
    console.error("获取剧本列表失败:", error);
  }
};

// 获取当前用户的剧本数据
const fetchScripts = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/api/getWordByUID/${props.uid}`);
    if (response.data.code === 200 && response.data.data) {
      const userScripts = {
        typename: '我的剧本',
        scripts: response.data.data,
      };
      scriptCount.value = response.data.data.length; // 更新剧本数量

      // 使用 emit 将 scriptCount 传递给父组件
      emit('update-script-count', scriptCount.value);

      // 检查是否已经存在 "我的剧本" 类别，避免重复插入
      const existingIndex = worklist.value.findIndex(category => category.typename === '我的剧本');
      if (existingIndex !== -1) {
        worklist.value[existingIndex] = userScripts;
      } else {
        worklist.value.push(userScripts);
      }
    } else {
      console.error('获取剧本数据失败:', response.data.message);
    }
  } catch (error) {
    console.error('API 请求失败:', error);
  }
};

// 页面加载时调用 API
onMounted(async () => {
  await initUser();
  await getWorkList();
  if (props.uid) {
    await fetchScripts();
  }
  loading.value = false; // 数据加载完成
});

// 跳转到详细信息页
const goToWorkProfile = (wid: string) => {
  router.push(`/workprofile/${wid}`);
};
</script>


<style scoped>
.work-container {
width: 100%;
height: auto;

}
.novel-image{
width: 170px;
height: 250px;
}
.work-card {
  margin: 20px auto 20px; /* 上边距和下边距可以保持原样，中间左右自动调整 */
  width: 215px;
  height: 350px;
}


.item-container {
display: flex; /* 设为Flexbox容器 */
align-items: center; /* 垂直居中对齐 */
}

.item-container h2 {
margin-right: 10px; /* 为文本和分割线之间添加间距 */
}

.item-container hr {
flex-grow: 1; /* 让分割线撑满剩余空间 */
border: none; /* 去掉默认边框 */
border-top: 1px solid #ccc; /* 自定义边框样式 */
}

</style>
